/**
 * 自定义节点示例代码
 * 以下示例展示了如何在自定义执行节点中编写不同类型的代码
 */

// 示例1: 基本字符串处理
const stringProcessingExample = `
function(params) {
  // 获取输入的字符串
  const text = params.text || '';
  
  // 进行处理
  const result = {
    original: text,
    uppercase: text.toUpperCase(),
    lowercase: text.toLowerCase(),
    length: text.length,
    words: text.split(' ').length
  };
  
  // 返回处理结果
  return result;
}
`;

// 示例2: 数学计算（比计算节点更复杂的计算）
const mathCalculationExample = `
function(params) {
  const { x, y, operation } = params;
  
  // 确保参数为数字
  const numX = Number(x) || 0;
  const numY = Number(y) || 0;
  
  let result;
  switch(operation) {
    case 'add':
      result = numX + numY;
      break;
    case 'subtract':
      result = numX - numY;
      break;
    case 'multiply':
      result = numX * numY;
      break;
    case 'divide':
      result = numY !== 0 ? numX / numY : 'Error: Division by zero';
      break;
    case 'power':
      result = Math.pow(numX, numY);
      break;
    default:
      result = numX + numY; // 默认加法
  }
  
  return {
    x: numX,
    y: numY,
    operation,
    result
  };
}
`;

// 示例3: 异步操作示例（模拟API调用延迟）
const asyncOperationExample = `
async function(params) {
  // 模拟异步操作
  const simulateApiCall = async (data, delay) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          success: true,
          data,
          timestamp: new Date().toISOString()
        });
      }, delay);
    });
  };
  
  // 获取输入参数
  const { data, delay } = params;
  const waitTime = Number(delay) || 1000; // 默认延迟1秒
  
  // 显示等待信息
  console.log(\`执行异步操作，等待\${waitTime}毫秒...\`);
  
  // 执行异步操作
  const result = await simulateApiCall(data, waitTime);
  
  // 返回结果
  return result;
}
`;

// 示例4: 数组处理
const arrayProcessingExample = `
function(params) {
  let array = params.array || [];
  const operation = params.operation || 'sort';
  
  // 如果输入是字符串，尝试解析为数组
  if (typeof array === 'string') {
    try {
      array = JSON.parse(array);
    } catch (e) {
      // 如果解析失败，按逗号分隔
      array = array.split(',').map(item => item.trim());
    }
  }
  
  // 确保array是数组类型
  if (!Array.isArray(array)) {
    array = [array];
  }
  
  let result;
  switch(operation) {
    case 'sort':
      result = [...array].sort();
      break;
    case 'reverse':
      result = [...array].reverse();
      break;
    case 'unique':
      result = [...new Set(array)];
      break;
    case 'count':
      result = array.length;
      break;
    case 'sum':
      result = array.reduce((sum, item) => sum + (Number(item) || 0), 0);
      break;
    default:
      result = array;
  }
  
  return {
    original: array,
    operation,
    result
  };
}
`;

// 示例5: JSON解析和处理
const jsonProcessingExample = `
function(params) {
  const jsonData = params.jsonData || '{}';
  const operation = params.operation || 'validate';
  
  try {
    // 解析JSON
    const data = typeof jsonData === 'object' ? jsonData : JSON.parse(jsonData);
    
    // 执行操作
    let result;
    switch(operation) {
      case 'validate':
        result = { valid: true, data };
        break;
      case 'keys':
        result = { keys: Object.keys(data) };
        break;
      case 'values':
        result = { values: Object.values(data) };
        break;
      case 'entries':
        result = { entries: Object.entries(data) };
        break;
      case 'flatten':
        // 简单扁平化，只处理一级嵌套
        const flat = {};
        for (const [key, value] of Object.entries(data)) {
          if (typeof value === 'object' && value !== null) {
            for (const [nestedKey, nestedValue] of Object.entries(value)) {
              flat[\`\${key}.\${nestedKey}\`] = nestedValue;
            }
          } else {
            flat[key] = value;
          }
        }
        result = { flattened: flat };
        break;
      default:
        result = { data };
    }
    
    return result;
  } catch (error) {
    return {
      valid: false,
      error: error.message
    };
  }
}
`;

export const customNodeExamples = {
  stringProcessingExample,
  mathCalculationExample,
  asyncOperationExample,
  arrayProcessingExample,
  jsonProcessingExample
};

export default customNodeExamples; 